package com.chaofao.synchronization.common;

import com.chaofao.synchronization.model.FileInfo;
import com.chaofao.synchronization.util.Fileutil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.List;

/**
 * Created by Chaofan at 2018-11-12 10:52
 * email:chaofan2685@qq.com
 **/
public class SaveInfoFileFilter implements FileFilter{

    //允许复制的文件类型
    private List<String> fileTypes;

    //目的地文件夹的路径
    private String destDirectory;

    //对比两个文件是否一致的算法（MD5/LENGTH）
    private String onlyArithmetic;

    private List<FileInfo> fileInfos;

    public SaveInfoFileFilter(String destDirectory, String onlyArithmetic, List<FileInfo> fileInfos, List<String> fileTypes) {
        this.destDirectory = destDirectory;
        this.onlyArithmetic = onlyArithmetic;
        this.fileInfos = fileInfos;
        this.fileTypes = fileTypes;
    }

    @Override
    public boolean accept(File pathname) {
        String name = pathname.getName();
        String newDir = destDirectory + "\\" + name;
        File newFile = new File(newDir);
        if (pathname.isDirectory()){
            try {
                Fileutil.fileInfos.add(new FileInfo(pathname,newFile,true));
                FileUtils.copyDirectory(pathname,newFile,new SaveInfoFileFilter(newDir,onlyArithmetic,fileInfos,fileTypes),true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //是文件，则判断是否开启白名单
            if (fileTypes != null && fileTypes.size() != 0){
                //开启白名单，先判断该文件是否在白名单中
                for (String type : fileTypes){
                    if (name.toUpperCase().endsWith(type)){
                        saveInfo(pathname,newFile);
                    }
                }
                return false;
            }else {
                saveInfo(pathname,newFile);
            }

        }
        return false;
    }

    private void saveInfo(File pathname,File newFile){
        FileInfo info = new FileInfo(pathname,newFile,onlyArithmetic);
        FileInfo info2 = new FileInfo(newFile,pathname,onlyArithmetic);
        if (info.equals(info2)){
            Fileutil.fileInfos.add(new FileInfo(pathname,newFile,false));
        }else {
            for (FileInfo info1 : fileInfos){
                if (new FileInfo(pathname,newFile,false).equals(info1)){
                    Fileutil.fileInfos.add(info1);
                }
            }
        }
    }

}
